package cn.bone.auth.security.base.advice;

import cn.bone.auth.security.base.exception.MyTestException;
import cn.bone.auth.security.base.exception.MyUserNotFindException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    //使用String做返回值,返回403页面
    @ExceptionHandler(AccessDeniedException.class)
    public String exception403(AccessDeniedException e){

        System.out.println("exception403---- " + e.getMessage());
        e.printStackTrace();

        // 403返回页面
        return "redirect:/403";
    }

    //返回json对象
    @ExceptionHandler(MyTestException.class)
    @ResponseBody
    public JSONObject myException(MyTestException e){

        JSONObject object = new JSONObject();
        object.put("message",e.getMessage());
        object.put("code","101");
        object.put("name","superbone");
        return object;
    }

    // 这里拦截自定义的用户不存在异常
    // 但是SpringSecurity会在过滤器中拦截,所以会跳转到失败页面
    // 还是需要在SpringSecurity的配置类中指定handle来处理
    @ExceptionHandler(MyUserNotFindException.class)
    @ResponseBody
    public JSONObject myUserNotFindException(MyUserNotFindException e){
        JSONObject object = new JSONObject();
        object.put("message",e.getMessage());
        object.put("code","102");
        object.put("name","用户找不到啊");
        return object;
    }

    //使用ModelAndView做返回值,返回500页面
    @ExceptionHandler(Exception.class)
    public ModelAndView exception500(Exception e){

        System.out.println("exception500---- " + e.getMessage());
        e.printStackTrace();

        // 500返回页面
        ModelAndView mv = new ModelAndView();
        //将异常信息放到request域中,基本上不会使用
        mv.addObject("errorMessage", e.getMessage());
        //其他异常
        // 500返回页面
        mv.setViewName("redirect:/500");
        return mv;
    }




}
